<template>
  <div class="versionUpdate">
    <div class="installation">
      <div class="aroundOf">新增版本</div>
      <!-- <p class="in_p" ><el-button @click="editOperation" v-if="editors" icon="el-icon-edit-outline">编辑</el-button></p> -->
      <el-form :model="versionUpdateForm" :rules="rules" ref="versionUpdateForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="版本号：" prop="versionNo" style="width: 60%;">
          <el-input v-model="versionUpdateForm.versionNo" placeholder="请选择安装包" :disabled="updatePackage"></el-input>
        </el-form-item>
        <el-form-item label="更新包：" prop="package" style="width: 60%;position: relative;">
          <el-input v-model="versionUpdateForm.package" placeholder="请上传安装包" style="width: 65%;" :disabled="updatePackage"></el-input>
          <!-- :action=" baseUrl + '/courseware/renewal'" -->
          <el-upload
            class="upload-demo"
            :action=" baseUrl + '/courseware/renewal'"
            :before-upload="beforeUpload"
            :headers="headersToken"
            multiple
            :show-file-list="false"
            :limit="1"
            :on-success="onSuccess"
            :file-list="fileList"
            :disabled="isDisabled">
            <el-button size="small" type="text" :disabled="isDisabled">选择安装包</el-button>
          </el-upload>
        </el-form-item>
        <!-- <el-form-item label="模式：">
          <el-radio-group v-model="versionUpdateForm.grey" @change="greyChange">
            <el-radio v-for="(item,index) in labelGery" :key="index" :label="item.name" :value="item.name"></el-radio>
          </el-radio-group>
        </el-form-item> -->
        <!-- <el-form-item label="选择机构：" prop="region" v-if="isGreys">
          <el-select v-model="versionUpdateForm.region" placeholder="请选择机构" style="width: 29%;" @change="reguionChange">
            <el-option v-for="item in goGray" :key="item.id" :label="item.name" :value="item.name" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>
        <div class="released" v-if="isGreys && tags.length > 0">
          灰度发布机构
          <div class="released_">
            <el-tag v-for="tag in tags" :key="tag" closable :disable-transitions="false" :type="tag.type" @close="handleClose(tag)"> {{tag}} </el-tag>
          </div>
        </div> -->

        <el-form-item label="选择版本：" prop="desc">
          <el-checkbox v-model="checkAll" @change="handleCheckAllChange" :disabled="isDisabled">全选</el-checkbox>
          <el-button type="text" style="margin-left: 160px;" @click="movingTo" v-if="isShow" :disabled="!isShow">移动至</el-button>
          <el-button type="text" v-else style="margin-left: 160px;" @click="movingTo" :disabled="!showIsIndeterminate.length > 0">移动至</el-button>
        </el-form-item>
        <div class="isIndeterminate">
          <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="city in cities" :label="city" :key="city" :disabled="isDisabled">{{ city }} </el-checkbox>
          </el-checkbox-group>
        </div>
        <el-form-item label="选择升级：" class="rade">
          <div class="upgrade_choose">
            <div class="u_choose">
              <el-checkbox-group v-model="someChoose.checkList">
                <el-checkbox v-for="city in someChoose.checkou" :label="city" :key="city" :disabled="isDisabled">{{city}}</el-checkbox>
              </el-checkbox-group>
              <p style="text-align: right;">
                <el-button type="primary" @click="remove" style="height: 40px;" :disabled="isDisabled">移 除</el-button>
              </p>
            </div>
            <div class="d_choose">
              <span>更新内容：</span>
              <el-input type="textarea" placeholder="请输入200个字符以内的更新说明" v-model="someArea.textarea" maxlength="200" show-word-limit :disabled="isDisabled"></el-input>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="强制升级：" class="rade">
          <div class="upgrade_choose">
            <div class="u_choose">
              <el-checkbox-group v-model="someChoose.checkListG">
                <el-checkbox v-for="city in someChoose.checkouG" :label="city" :key="city" :disabled="isDisabled">{{ city }}</el-checkbox>
              </el-checkbox-group>
              <p style="text-align: right;">
                <el-button type="primary" @click="removeG" style="height: 40px;" :disabled="isDisabled">移 除</el-button>
              </p>
            </div>
            <div class="d_choose">
              <span>更新内容：</span>
              <el-input type="textarea" placeholder="请输入200个字符以内的更新说明" v-model="someArea.text" maxlength="200" show-word-limit :disabled="isDisabled"></el-input>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="不升级：" class="rade">
          <div class="upgrade_choose">
            <div class="u_choose">
              <el-checkbox-group v-model="someChoose.checkListB">
                <el-checkbox v-for="city in someChoose.checkouB" :label="city" :key="city" :disabled="isDisabled">{{city}}</el-checkbox>
              </el-checkbox-group>
              <p style="text-align: right;">
                <el-button type="primary" @click="removeB" style="height: 40px;" :disabled="isDisabled">移 除</el-button>
              </p>
            </div>
            <div class="d_choose">
              <span>更新内容：</span>
              <el-input type="textarea" placeholder="请输入200个字符以内的更新说明" v-model="someArea.textB" maxlength="200" show-word-limit :disabled="isDisabled"></el-input>
            </div>
          </div>
        </el-form-item>
        <p style="text-align: center;margin-top: 50px;width: 90%;">
          <el-button type="primary" @click="submitForm('versionUpdateForm')" style="width: 120px;" :disabled="isDisabled">更新</el-button>
        </p>
      </el-form>
    </div>
    <!-- 移动至弹框 -->
    <el-dialog title="移动至" :visible.sync="popUp" width="30%" center class="popUp">
      <el-button @click="upgrade">选择升级</el-button>
      <el-button @click="upgradeMo">强制升级</el-button>
      <el-button @click="upgradeNo">不升级</el-button>
    </el-dialog>
  </div>
</template>

<script>
import { base } from '../../api/axiosFun';
export default {
  data() {
    return {
      headersToken: {  // 请求时添加token
        Authorization: localStorage.getItem('logintoken'),
      },
      baseUrl: '',
      popUp: false,
      checkAll: false,   // 控制全选 选中和未选择
      checkedCities: [],
      cities: [],
      isGreys: false,
      versionUpdateForm: {
        versionNo: '',
        package: '',
        grey: '',
        region: ''
      },
      time: '', //文件上传时间
      rules: {
        versionNo: [ { required: true, message: '请输入版本号', trigger: 'blur' }],
        package: [ { required: true, message: '请上传安装包', trigger: 'blur' }]
      },
      labelGery: [{name: '正式'},{name: '灰度'}], // 选择模式
      fileList: [],   
      someChoose: {
        checkou: [],  //  页面选择升级
        checkList: [],  //  弹框选择升级
        checkListG: [], //  弹框强制升级
        checkouG: [],   // 页面强制升级
        checkListB: [], // 弹框不升级
        checkouB: [], // 页面不升级
      },
      someIngse: {    // 这个是详情进去后获取到的三个不同版本中的数据存储到这里 后续进行拼接作用
        original: [], // 原来刚进入时的版本号选择升级
        mandatory: [],  // 强制
        upgrade: [],  // 不升级
      },
      tags: [] ,  //  灰度发布机构标签
      someArea: {  // 这个是四个更新的内容输入
        text: '',   //  强制
        textarea: '', //  选择
        textB: '' //  不升级
      },
      isDisabled: true, // 控制详情进入不让其修改，只有点击编辑才允许其修改
      editors: false,  // 控制编辑的显隐
      updatePackage: false, // 控制上传文件成功后禁用掉
      newGrey: {},  //  跳转过来的数据
      goGray: [{ id: 1, name: 'xxx机构', disabled: false, },{ id: 2, name: 'zzz机构', disabled: false, }],
      showIsIndeterminate: [],  //  选择版本选中的数组
      isShow: false,  //  选择版本全选
      typeChoose: '', //  选择类型选择升级为1，强制升级为2，不升级为3
      img: '', // 上传版本的路径
      capacity: '', //上传的版本大小
      md: '', // 上传文件的加密
      soneList: {},
    }
  },
  mounted() {
    this.baseUrl = base;
    if(sessionStorage.getItem('versionAdd') == 'versionAdd') {
      this.isDisabled = this.editors = false;
      this.updatePackage = true;
      this.newVersion(); // 更新进来选择版本信息
    } else {
      this.detailsList(); // 详情进来获取的数据
      this.version();
      this.editors = true;
      this.updatePackage = true;
      this.newGrey = JSON.parse(sessionStorage.getItem('routerThis'));
      this.versionUpdateForm.versionNo = this.newGrey.name;  // 版本号回显
      this.versionUpdateForm.package = this.newGrey.iname; // 回显更新包名称
      // this.versionUpdateForm.pattern = this.newGrey.pattern;
      // if(this.newGrey.pattern == '2') {
      //   this.isGreys = true;
      //   this.versionUpdateForm.grey = '灰度';
      // } else {
      //   this.isGreys = false;
      //   this.versionUpdateForm.grey = '正式';
      // }
    }
  },
  methods: {
    // 获取所有版本
    version() { this.$http.setUpthe.version({id: JSON.parse(sessionStorage.getItem('routerThis')).id}).then( res=> { this.cities = res.data; }) },
    newVersion() { this.$http.setUpthe.version().then( res=> { this.cities = res.data; }) },
    // 列表页详情进来
    detailsList(){
      this.$http.setUpthe.coursewareListDetails({id: JSON.parse(sessionStorage.getItem('routerThis')).id}).then( res => {
        this.someChoose.checkou = this.someIngse.original = res.data.banQiang2.name;    // 选择
        this.someArea.textarea = res.data.banQiang2.content;
        this.someChoose.checkouG = this.someIngse.mandatory = res.data.banQiang1.name;   // 强制
        this.someArea.text = res.data.banQiang1.content;
        this.someChoose.checkouB = this.someIngse.upgrade = res.data.banQiang3.name;    // 不升级
        this.someArea.textB = res.data.banQiang3.content;
        this.soneList = res.data;
        console.log(this.someIngse.original,this.someIngse.mandatory,this.someIngse.upgrade)
      })
    },
    // 编辑操作
    editOperation(){ this.isDisabled = false; },
    // 模式切换，数据清除
    greyChange(val){
      if(val == '灰度'){
        this.isGreys = true;
      } else {
        this.isGreys = false;
        this.versionUpdateForm.region = '';
        this.tags = [];
      }
    },
    // 弹框选择升级
    upgrade() {
      this.$confirm('此操作将移动至选择升级, 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '移动至选择升级成功!'
        });
        this.typeChoose = 2;
        this.popUp = false;
        if(this.someIngse.original == null || this.someChoose.checkou == null) {
          this.someChoose.checkou = this.someIngse.original = []
        } else { this.someChoose.checkou = this.someIngse.original; }
        if(this.someIngse.original == null) { this.someChoose.checkou = [...this.checkedCities, ...this.someChoose.checkou] } 
        else { this.someChoose.checkou = [...this.checkedCities, ...this.someIngse.original] }
        if(this.checkAll) { this.cities = [] }
        const newAcheck = Array.from(new Set(this.someChoose.checkou));  // 数组去重
        this.someChoose.checkou = newAcheck;
        this.someIngse.original = this.someChoose.checkou;
        this.multipleChoice();
        if(this.cities.length == 0) { this.showIsIndeterminate.length = 0 }
        this.someChoose.checkList = [];
        this.checkedCities = [];
        this.checkAll = false;
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消移动至选择升级'
        });
      });
    },
    // 弹框强制升级
    upgradeMo() {
      this.$confirm('此操作将移动至强制升级, 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '移动至强制升级成功!'
        });
        this.typeChoose = 1;
        this.popUp = false;
        if(this.someIngse.mandatory == null || this.someChoose.checkouG == null) { this.someChoose.checkouG = this.someIngse.mandatory = [] } 
        else { this.someChoose.checkouG = this.someIngse.mandatory; }
        if(this.someIngse.mandatory == null) { this.someChoose.checkouG = [...this.checkedCities, ...this.someChoose.checkouG] } 
        else { this.someChoose.checkouG = [...this.checkedCities, ...this.someIngse.mandatory] } // 这三个的这个是拼接数组 （把原来数组里有的和新添加进来的进行拼接）
        if(this.checkAll) { this.cities = [] }
        const newAcheck = Array.from(new Set(this.someChoose.checkouG));  // 数组去重
        this.someChoose.checkouG = newAcheck;
        this.someIngse.mandatory = this.someChoose.checkouG;
        this.multipleChoice();
        if(this.cities.length == 0) { this.showIsIndeterminate.length = 0 }
        this.someChoose.checkListG = [];
        this.checkedCities = [];
        this.checkAll = false;
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消移动至强制升级'
        });
      });
    },
    // 弹框不升级
    upgradeNo() {
      this.$confirm('此操作将移动至不升级, 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '移动至不升级成功!'
        });
        this.typeChoose = 3;
        this.popUp = false;
        if(this.someIngse.upgrade == null || this.someChoose.checkouB == null) { 
          this.someChoose.checkouB = this.someIngse.upgrade = [] 
        } else { 
          this.someChoose.checkouB = this.someIngse.upgrade;
        }
        if(this.someIngse.upgrade == null) { 
          this.someChoose.checkouB = [...this.checkedCities, ...this.someChoose.checkouB] 
        } else { 
          this.someChoose.checkouB = [...this.checkedCities, ...this.someIngse.upgrade] 
        } // 这三个的这个是拼接数组 （把原来数组里有的和新添加进来的进行拼接）
        if(this.checkAll) { this.cities = [] }
        const newAcheck = Array.from(new Set(this.someChoose.checkouB));  // 数组去重
        this.someChoose.checkouB = newAcheck;
        this.someIngse.upgrade = this.someChoose.checkouB;
        this.multipleChoice();
        if(this.cities.length == 0) { this.showIsIndeterminate.length = 0 }
        this.someChoose.checkListB = [];
        this.checkedCities = [];
        this.checkAll = false;
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '移动至不升级已取消'
        });
      });
    },
    // 选择升级移除
    remove() { 
      this.publicMethods(this.someChoose.checkList,this.someChoose.checkou) 
      if(sessionStorage.getItem('versionAdd') == 'versionAdd') { 
        if(this.someChoose.checkList.length > 0) {
          this.newVersion();
        }
      } else {
        this.someChoose.checkList.map( item => {
          this.cities.splice(0,0,item);
          this.singleWeighted();
        })
      }
      // this.someChoose.checkou = [];
    },
    // 强制升级移除
    removeG(){ 
      this.publicMethods(this.someChoose.checkListG,this.someChoose.checkouG)
      if(sessionStorage.getItem('versionAdd') == 'versionAdd') {
        if(this.someChoose.checkListG.length > 0) {
          this.newVersion();
        }
      } else {
        this.someChoose.checkListG.map( item => {
          this.cities.splice(0,0,item);
          this.singleWeighted();
        })
      }
      // this.someChoose.checkouG = [];
    },
    // 不升级移除
    removeB(){ 
      this.publicMethods(this.someChoose.checkListB,this.someChoose.checkouB);
      if(sessionStorage.getItem('versionAdd') == 'versionAdd') { 
        if(this.someChoose.checkListB.length > 0) {
          this.newVersion();
        }
      } else {
        this.someChoose.checkListB.map( item => {
          this.cities.splice(0,0,item);
          this.singleWeighted();
        })
      }
      // this.someChoose.checkouB = [];
    },
    // 移除的公共方法
    publicMethods(arr,arrList){
      arr.filter( item => {
        arrList.filter( (i,index) => {
          if(item == i){
            arrList.splice(index,1);
          }
        })
      })
    },
    // 单个移除选择版本中去重
    singleWeighted() {
      const newAcheck = [];
      this.cities.forEach( item => {
        if(!newAcheck.includes(item)) {
          newAcheck.push(item)
        }
      })
      this.cities = newAcheck;
    },
    // 选择版本单选或者多选但是不全选操作
    multipleChoice() {
      this.cities.filter( item => {
        this.showIsIndeterminate.filter( i => {
          if(item == i) {
            this.cities.splice(this.cities.indexOf(i),this.checkedCities.length);
          }
        })
      })
    },
    // --------------------------------------------------------------------------
    // 灰度标签  目前不用
    handleClose(tag) {
      this.tags.splice(this.tags.indexOf(tag), 1);
      this.goGray.filter( item => {
        if(this.tags.length == 0) {
          item.disabled = false;
          this.versionUpdateForm.region = '';
        }
        if(item.name == tag){
          item.disabled = false;
        }
      })
    },
    // 移动至
    movingTo(){ this.popUp = true; },
    // 文件上传之前
    beforeUpload(file) {
      this.$message({
        showClose: true,
        message: '正在上传，请稍后！'
      });
    },
    // 这个是文件上传成功后
    onSuccess(response, file, fileList){ 
      if(response.code == 200) {
        this.versionUpdateForm.package = response.data.iname;
        this.time = response.data.createDate;
        this.img = response.data.img;
        this.capacity = response.data.capacity;
        this.md = response.data.md;
        this.versionUpdateForm.versionNo = response.data.versionName;
        this.$message({
          showClose: true,
          message: '文件已经上传成功',
          type: 'success'
        });
      }
      // console.log(response, file, fileList)
    },
    // ------------------------------------------------
    //  选择版本 的全选按钮
    handleCheckAllChange(val) {
      this.isShow = val;
      this.checkedCities = val ? this.cities : [];  // 全选选中的数据
      this.isIndeterminate = val;
    },
    // 选中版本 里面选中的数组方法
    handleCheckedCitiesChange(value) {
      this.showIsIndeterminate = value;
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.cities.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
    },
    // ------------------------------------------------
    // 更新按钮操作
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(sessionStorage.getItem('versionAdd') == 'versionAdd') {  // 这个是更新进来的更新按钮
            this.$http.setUpthe.coursewareLsave({name: this.versionUpdateForm.versionNo,createDate: this.time,iname: this.versionUpdateForm.package ,allof: this.isShow == true ? '1' : '2',banQiang1: {name: this.someChoose.checkouG,status: 1,content: this.someArea.text},banQiang2: {name: this.someChoose.checkou,status: 2,content: this.someArea.textarea},banQiang3: {name: this.someChoose.checkouB,status: 3,content: this.someArea.textB},status: this.typeChoose == '3' ? '2' : this.typeChoose == '2' ? '2' : '1',img: this.img,capacity: this.capacity,content: '',md: this.md}).then( res => {
              // console.log(res)
              if(res.code == 200) {
                this.$message({
                  showClose: true,
                  message: '恭喜你，创建成功',
                  type: 'success'
                });
                sessionStorage.removeItem('versionAdd');
                setTimeout( () => {
                  this.$router.push({path: "/setUpThe"});
                },500)
              } else if(res.code == 530) {  // 版本重复 
                this.$message({
                  showClose: true,
                  message: res.errorMessage,
                  type: 'warning'
                });
              }
            })
          } else {  // 这个是详情进来的编辑
            this.$http.setUpthe.coursewareLsave({id: JSON.parse(sessionStorage.getItem('routerThis')).id,name: this.versionUpdateForm.versionNo,createDate: this.time,iname: this.versionUpdateForm.package ,allof: this.isShow == true ? '1' : '2',banQiang1: {name: this.someChoose.checkouG,status: 1,content: this.someArea.text,id: this.soneList.banQiang1.id},banQiang2: {name: this.someChoose.checkou,status: 2,content: this.someArea.textarea,id: this.soneList.banQiang2.id},banQiang3: {name: this.someChoose.checkouB,status: 3,content: this.someArea.textB,id: this.soneList.banQiang3.id},status: this.typeChoose == '3' ? '2' : this.typeChoose == '2' ? '2' : '1',img: this.img,capacity: this.capacity,content: '',md: this.md}).then( res => {
              if(res.code == 200) {
                this.$message({
                  showClose: true,
                  message: '恭喜你，修改成功',
                  type: 'success'
                });
                sessionStorage.removeItem('versionAdd');
                setTimeout( () => {
                  this.$router.push({path: "/setUpThe"})
                },500)
              }
            })
          }
        } else {
          return false;
        }
      });
    },
    // 选择机构 添加到右侧回复机构框框里面
    reguionChange(val) {
      this.goGray.filter( item => {
        if(item.name === val){
          item.disabled = true;
        }
      })
      this.tags.push(val);
    }
  }
}
</script>

<style scoped>
@import '../../assets/css/setUpThe/versionUpdate.scss';
</style>